﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;

namespace CheckUser
{
    public partial class Form1 : Form
    {
        public struct FILETIME
        {
            public Int32 dwLowDateTime;
            public Int32 dwHighDateTime;
        }

        public TimeSpan preidleTime = new TimeSpan();
        public TimeSpan prekernelTime = new TimeSpan();
        public TimeSpan preuserTime = new TimeSpan();

        public TimeSpan idleTime = new TimeSpan();
        public TimeSpan kernelTime = new TimeSpan();
        public TimeSpan userTime = new TimeSpan();

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool GetSystemTimes(out TimeSpan lpIdleTime, out TimeSpan lpKernelTime, out TimeSpan lpUserTime);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bool res = false;
            res = GetSystemTimes(out preidleTime, out prekernelTime, out preuserTime);
            if (!res)
            {
                MessageBox.Show("error");
                return;
            }
            Thread.Sleep(1000);
            this.timer1.Interval = 1000;
            this.timer1.Enabled = true;
            //WindowsIdentity identity = WindowsIdentity.GetCurrent();
            //for (int i = 0; i < identity.Groups.Count; i++)
            //{
            //    this.richTextBox1.AppendText(identity.Groups[i].Value + "(" + Environment.UserName+ ")\n");
            //    this.richTextBox1.AppendText(Environment.OSVersion.Platform.ToString()+"\n");
            //}
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            bool res = false;
            res = GetSystemTimes(out idleTime, out kernelTime, out userTime);
            if (!res)
            {
                MessageBox.Show("error");
                return;
            }
            Int64 idle = idleTime.Subtract(preidleTime).Ticks;
            Int64 kernel = kernelTime.Subtract(prekernelTime).Ticks;
            Int64 user = userTime.Subtract(preuserTime).Ticks;

            Int64 cpu = (kernel + user - idle) * 100 / (kernel + user);
            Int64 cpuidle = (idle) * 100 / (kernel + user);

            this.richTextBox1.AppendText("CPU利用率:" + cpu + "%       CPU空闲率:" + cpuidle + "%\n");

            preidleTime = idleTime;
            prekernelTime = kernelTime;
            preuserTime = userTime;

        }




    }
}
